package org.dev.biz_search

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import org.dev.`as`.project.common.http.ApiFactory
import org.dev.hi.library.cache.HiStorage
import org.dev.hi.library.executor.HiExecutor
import org.dev.hi.library.restful.HiCallback
import org.dev.hi.library.restful.HiResponse
import org.dev.pub.model.GoodsModel
import java.security.Key

/**
 * Author WenPing
 * CreateTime 2021/8/26.
 * Description:实现搜索记录的本地保存/查询/更新/删除
 */
class SearchViewModel : ViewModel() {

    var keywords: ArrayList<KeyWord>? = null
    var pageIndex = PAGE_INIT_INDEX

    companion object {
        const val PAGE_SIZE = 10
        const val PAGE_INIT_INDEX = 1

        const val KEY_SEARCH_HISTORY = "search_|history"
        const val MAX_HISTORY_SIZE = 10
    }

    fun quickSearch(key: String): LiveData<List<KeyWord>?> {
        val liveData = MutableLiveData<List<KeyWord>?>()
        ApiFactory
            .create(SearchApi::class.java)
            .quickSearch(key)
            .enqueue(
                object : HiCallback<QuickSearchList> {
                    override fun onSuccess(hiResponse: HiResponse<QuickSearchList>) {
                        liveData.postValue(hiResponse.data?.list)
                    }

                    override fun onFailed(throws: Throwable) {
                        liveData.postValue(null)
                    }
                }
            )
        return liveData
    }

    var goodsSearchLiveData = MutableLiveData<List<GoodsModel>?>()
    fun goodsSearch(keyWord: String, loadInit: Boolean) {
        if (loadInit) pageIndex = PAGE_INIT_INDEX
        ApiFactory
            .create(SearchApi::class.java)
            .goodsSearch(
                keyWord,
                pageIndex, PAGE_SIZE
            )
            .enqueue(object : HiCallback<GoodsSearchList> {
                override fun onSuccess(hiResponse: HiResponse<GoodsSearchList>) {
                    goodsSearchLiveData.value = hiResponse.data?.list
                    pageIndex++
                }

                override fun onFailed(throws: Throwable) {
                    goodsSearchLiveData.postValue(null)
                }
            })
    }

    /**
     * 把关键词的集合保存到数据库中
     */
    fun saveHistory(keyWord: KeyWord) {
        if (keywords == null) {
            keywords = ArrayList()
        }
        keywords?.apply {
            if (contains(keyWord)) {
                remove(keyWord)
            }
            add(0, keyWord)
            if (this.size > MAX_HISTORY_SIZE) {
                // 移除多出的几个元素
                dropLast(this.size - MAX_HISTORY_SIZE)
            }
            // 开启一个线程池,把集合保存到数据库中
            HiExecutor
                .execute(runnable = Runnable {
                    HiStorage.saveCache(KEY_SEARCH_HISTORY, keywords)
                })
        }
    }

    /**
     * 查询数据库中的数据
     */
    fun queryLocalHistory(): LiveData<ArrayList<KeyWord>> {
        val liveData = MutableLiveData<ArrayList<KeyWord>>()
        HiExecutor.execute(runnable = Runnable {
            keywords = HiStorage.getCache<ArrayList<KeyWord>>(KEY_SEARCH_HISTORY)
            liveData.postValue(keywords)
        })
        return liveData
    }

    /**
     * 清空数据库中的数据
     */
    fun clearHistory() {
        HiExecutor.execute(
            runnable = Runnable {
                HiStorage.deleteCache(KEY_SEARCH_HISTORY)
            }
        )
    }


}